<template>
    <el-dialog
        v-model="distributionVisible"
        width="80%"
        draggable
        :show-close="false"
        :close-on-click-modal="false"
        @open="getAllDataListEvent"
        @close="clearAllProductListEvent"
    >
        <!-- 自定义头部 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">
                    材质：
                    <el-text type="primary">{{ props.stockInfo.materialQuality }}</el-text>
                    尺寸：
                    <el-text type="primary">{{ props.stockInfo.size }}</el-text>
                    库存分销
                    <el-text type="primary">{{ props.stockInfo.remainingNumber }}</el-text>
                    张
                </h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>
        <!-- 内容 -->
        <div class="flex flex-wrap justify-end">
            <el-autocomplete v-model="selectedProduct" :fetch-suggestions="querySearch" clearable placeholder="请搜索关键字" @select="handleSelect" />
            <div class="flex items-center mt-2">
                <el-select v-model="distributionData.orderStatus" placeholder="请选择订单状态" style="width: 160px">
                    <el-option v-for="item in orderStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-input-number v-model="num" :min="1" :max="props.stockInfo.remainingNumber" style="margin-left: 12px; width: 160px">
                    <template #suffix>
                        <span>张</span>
                    </template>
                </el-input-number>
                <el-button class="ml-2" :disabled="!selectedProduct" type="primary" plain @click="transferPurchaseEvent">确认</el-button>
            </div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { getAllCustomerList } from '@/api/customer';
import { getAllProductList } from '@/api/product';
import { transferPurchase } from '@/api/purchase';
import { CircleCloseFilled } from '@element-plus/icons-vue';

// 定义limitDta接口
interface LimitData {
    length: number;
    width: number;
}

// 定义model  变量
const distributionVisible = defineModel('distributionVisible', { type: Boolean, default: false, required: true });
const limitData = defineModel<LimitData>('limitData', { required: true });

// 定义props 接口
const props = defineProps<{ stockInfo: { _id: string; size: string; crimping: string; materialQuality: string; remainingNumber: number } }>();

/* ******************************通用属性/方法****************************** */
// 所有产品列表
const productList = reactive<AjaxResponse['productList']>([]);
// 所有客户列表
const customerList = reactive<AjaxResponse['customerList']>([]);

// 对比比较事件
const comparisonEvent = (widthOrLength: number, product: AjaxResponse['productList'][0], comparisonType: 'length' | 'width') => {
    if (comparisonType == 'length') {
        // 准备对比数据
        let pre = 0;
        let _pre = 0;

        // 如果存在面纸
        if (product.tissueSize !== '') {
            pre = Number(product.tissueSize.split('*')[0]);
        }
        // 如果存在瓦楞
        if (product.corrugatedSize !== '') {
            _pre = Number(product.corrugatedSize.split('*')[0]);
        }

        // 如果都不存在
        if (product.tissueSize == '' && product.corrugatedSize == '') {
            return false;
        }

        // 产品数据小于等于库存纸规格
        if (pre <= widthOrLength && _pre <= widthOrLength) {
            return true;
        }
        return false;
    }

    if (comparisonType == 'width') {
        let next = 0;
        let _next = 0;
        // 如果存在面纸
        if (product.tissueSize !== '') {
            next = Number(product.tissueSize.split('*')[1]);
        }
        // 如果存在瓦楞
        if (product.corrugatedSize !== '') {
            _next = Number(product.corrugatedSize.split('*')[1]);
        }

        // 如果都不存在
        if (product.tissueSize == '' && product.corrugatedSize == '') {
            return false;
        }

        // 产品数据小于等于库存纸规格
        if (next <= widthOrLength && _next <= widthOrLength) {
            return true;
        }
        return false;
    }
};
// 匹配客户信息事件
const matchCustomerInfo = (customerId: string): string => {
    let customerAbbreviation: string = '';
    for (let index = 0; index < customerList.length; index++) {
        const customer = customerList[index];
        if (customer._id == customerId) {
            customerAbbreviation = customer.customerAbbreviation;
            return customerAbbreviation;
        }
    }
    return customerAbbreviation;
};
// 获取所有产品列表
const getAllDataListEvent = async () => {
    // 加载所有客户
    const customers = await getAllCustomerList();
    customers.data.forEach((item) => {
        customerList.push(item);
    });
    // 加载所有产品
    const products = await getAllProductList();
    products.data.forEach((item) => {
        // 对数据进行筛选
        item.products.forEach((product) => {
            // 验证该产品是否匹配限制
            if (comparisonEvent(limitData.value.length, product, 'length') && comparisonEvent(limitData.value.width, product, 'width')) {
                // 添加其他属性
                product.customerId = item.customerId;
                product.value = `🚀 产品名称：${product.productName} -- 📌 -- 面纸规格：${product.tissueSize || '/'} -- 📌 -- 瓦楞规格：${
                    product.corrugatedSize || '/'
                } -- 📌 -- 材质：${product.materialQuality || '/'}`;
                productList.push(product);
            }
        });
    });
};
// 清空所有产品列表
const clearAllProductListEvent = () => {
    productList.length = 0;
    selectedProduct.value = '';
    distributionData.customerId = '';
    distributionData.customerAbbreviation = '';
    distributionData.orderStatus = 'primary';
    distributionData.productId = '';
    distributionData.productName = '';
    distributionData.productSize = '';
    distributionData.tissueSize = '';
    distributionData.corrugatedSize = '';
    distributionData.materialQuality = '';
    distributionData.crimping = '';
    distributionData.spell = 0;
};

/* ******************************填充框属性/方法****************************** */
// 自动填充框被选择的数据
const selectedProduct = ref('');
// 自动填充框搜索
const querySearch = (queryString: string, cb: any) => {
    // 过滤数据
    const results = queryString ? productList.filter(createFilter(queryString)) : productList;
    // call callback function to return suggestions
    cb(results);
};
// 过滤方法
const createFilter = (queryString: string) => {
    return (restaurant) => {
        return restaurant.value.indexOf(queryString) !== -1;
    };
};
// 自动填充框被选择
const handleSelect = (item: any) => {
    // 压线检测
    if (props.stockInfo.crimping !== item.crimping) {
        ElMessage({
            message: '压线不匹配，请慎重选择',
            type: 'warning',
            grouping: true,
        });
    }

    distributionData.customerId = item.customerId;
    distributionData.customerAbbreviation = matchCustomerInfo(item.customerId);
    distributionData.orderStatus = 'primary';
    distributionData.productId = item._id;
    distributionData.productName = item.productName;
    distributionData.productSize = item.productSize;
    distributionData.tissueSize = item.tissueSize;
    distributionData.corrugatedSize = item.corrugatedSize;
    distributionData.materialQuality = item.materialQuality;
    distributionData.crimping = item.crimping;
    distributionData.spell = item.spell;
};

/* ******************************分销属性/方法****************************** */
// 分销数据
const distributionData = reactive<AjaxRequest['distributionData']>({
    customerId: '',
    customerAbbreviation: '',
    orderStatus: 'primary',
    productId: '',
    productName: '',
    productSize: '',
    tissueSize: '',
    corrugatedSize: '',
    materialQuality: '',
    crimping: '',
    spell: 0,
});
// 订单状态
const orderStatusOptions = [
    {
        value: 'primary',
        label: '正常',
    },
    {
        value: 'warning',
        label: '加急',
    },
    {
        value: 'danger',
        label: '特急',
    },
];
// 分销数量
const num = ref(1);
// 确认分销
const transferPurchaseEvent = () => {
    // 关闭弹窗
    transferPurchase(props.stockInfo._id, num.value, distributionData).then(() => {
        ElMessage.success('分销成功');
        distributionVisible.value = false;
    });
};
</script>

<style scoped lang="scss">
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
</style>
